// 引入
import type { DataYao } from '@/Type/indeType'
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'

// 定义类型
export interface CartItem extends DataYao {
  count: number
  check: boolean
}

// 创建
export const useCartStore = defineStore('cart', () => {
  const cartList = ref<CartItem[]>(
    localStorage.getItem('cartList') ? JSON.parse(localStorage.getItem('cartList') as string) : []
  )

  const saveLocalStorage = () => {
    localStorage.setItem('cartList', JSON.stringify(cartList.value))
  }

  // 加入购物车
  const addCart = (item: DataYao) => {
    const index = cartList.value.findIndex((v) => v.restorativesid === item.restorativesid)
    if (index !== -1) {
      cartList.value[index].count += 1
    } else {
      cartList.value.push({
        ...item,
        count: 1,
        check: false
      })
    }
    console.log(cartList.value)
    saveLocalStorage()
  }
  const DeleteCart = (id: number) => {
    cartList.value = cartList.value.filter((v) => v.restorativesid !== id)
    saveLocalStorage()
  }

  watch(cartList, () => {
    console.log('2')
    saveLocalStorage()
  })

  watch(cartList.value, () => {
    console.log('1')
    saveLocalStorage()
  })

  return {
    addCart,
    DeleteCart,
    cartList,

  }
})
